package org.mspring.mlog.web.module.admin.self.auth;

import java.io.IOException;
import java.net.URISyntaxException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.web.module.admin.Admin_AdminWidget;
import org.mspring.platform.config.ConfigService;
import org.mspring.platform.security.SecurityUtils;
import org.mspring.platform.security.entity.User;
import org.mspring.platform.utils.PropertyConfigurer;
import org.mspring.platform.utils.RequestUtils;
import org.mspring.platform.web.ResponseEntity;
import org.mspring.platform.web.freemarker.widget.stereotype.Widget;
import org.mspring.platform.weibo.tencent.TencentOAuthService;
import org.mspring.platform.weibo.tencent.TencentUserinfoService;
import org.mspring.platform.weibo.tencent.entity.TencentUserinfo;
import org.mspring.platform.weibo.tencent.entity.dto.TencentAuth;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 腾讯微博授权
 *
 * @author Gao Youbo
 * @since 2014年5月19日
 */
@Widget
@RequestMapping("/admin/self/auth/tencent")
public class Admin_TencentAuthWidget extends Admin_AdminWidget {

    private static final Logger log = LoggerFactory.getLogger(Admin_TencentAuthWidget.class);

    @Autowired
    private ConfigService configService;
    @Autowired
    private TencentOAuthService tencentOAuthService;
    @Autowired
    private TencentUserinfoService tencentUserinfoService;
    @Autowired
    private PropertyConfigurer propertyConfigurer;

    private static final String REDIRECT_URL = "/admin/self/auth/tencent/authorize_callback";

    /**
     * A.请求code
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/authorize")
    public String authorize(HttpServletRequest request, HttpServletResponse response, Model model) {
        String clientId = propertyConfigurer.getString("tencent.appkey");
        String redirectUrl = configService.getConfig("siteurl") + REDIRECT_URL;
        String url = tencentOAuthService.getAuthorizeUrl(clientId, redirectUrl);
        return "redirect:" + url;
    }

    /**
     *
     * B.请求accesstoken
     *
     * @param request
     * @param response
     * @param model
     * @return
     * @throws URISyntaxException
     * @throws IOException
     */
    @RequestMapping("/authorize_callback")
    public String authorize_callback(HttpServletRequest request, HttpServletResponse response, Model model) throws IOException, URISyntaxException {
        String clientId = propertyConfigurer.getString("tencent.appkey");
        String clientSecret = propertyConfigurer.getString("tencent.appsecret");

        String code = RequestUtils.getRequestParameterAsString(request, "code"); // 用来换取accesstoken的授权码，有效期为10分钟
        String openid = RequestUtils.getRequestParameterAsString(request, "openid"); // 用户统一标识，可以唯一标识一个用户
        String openkey = RequestUtils.getRequestParameterAsString(request, "openkey"); // 与openid对应的用户key，是验证openid身份的验证密钥

        String redirectUrl = configService.getConfig("siteurl") + REDIRECT_URL;
        try {
            TencentAuth tencentAuth = tencentOAuthService.accessToken(clientId, clientSecret, code, redirectUrl);
            User user = SecurityUtils.getCurrentUser();
            tencentUserinfoService.insertOrUpdate(user.getId(), openid, openkey, tencentAuth.getAccessToken(), tencentAuth.getRefreshToken(), tencentAuth.getExpiresIn());
            return "/admin/self/auth/tencent/success";
        } catch (Exception e) {
            log.error("请求accesstoken失败", e);
            return "/admin/self/auth/tencent/failure";
        }

    }

    /**
     * 获取当前腾讯微博的授权信息
     *
     * @param request
     * @param response
     * @param model
     * @return
     */
    @RequestMapping("/info")
    @ResponseBody
    public ResponseEntity info(HttpServletRequest request, HttpServletResponse response, Model model) {
        User user = SecurityUtils.getCurrentUser();
        TencentUserinfo tencentUserinfo = tencentUserinfoService.findByUserId(user.getId());
        ResponseEntity rsp = ResponseEntity.getInstance();
        rsp.put("tencentUserinfo", tencentUserinfo);
        return rsp;
    }

}
